import Vue from 'vue'

const state = {
  chooseDepart: 0,
  chooseEmployees: 0,
  employeesCount: {
    onJob: 0, // 在职员工
    offJob: 0, // 离职员工
    admin: 0 // 管理员
  }
}

// 获取数据
const getters = {
  getEmployeesCount: state => {
    return state.employeesCount
  },
  getChooseEmployees: state => {
    return state.chooseEmployees
  },
  getChooseDepart: state => {
    return state.chooseDepart
  }
}

// 转变 更新数据
const mutations = {
  syncContacts (state) {
    let coId = Vue.prototype.$store.getters.currentUser.coId
    if (!coId) {
      return
    }
    Vue.prototype.$DesignDB.contactLstTime(coId, function (lastDep, lastEmp) {
      let startTime = lastDep ? lastDep.modifyTime : null
      let empTime = lastEmp ? lastEmp.modifyTime : null
      let query = {
        'query.time': startTime,
        'query.empTime': empTime
      }
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.companyServer}/front/contact/loadNewCompanyData.htm`,
        closeSaveRequest: true,
        data: Vue.prototype.$qs.stringify(query)
      }).then(res => {
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          return
        }
        let contacts = res.data.contacts
        let departments = contacts.departments
        if (departments) {
          Vue.prototype.$store.commit('updateDeartments', departments)
        }
        let employees = contacts.employeeFronts
        if (employees) {
          Vue.prototype.$store.commit('updateEmployees', employees)
        }
      })
    })
  },
  updateDeartments (state, departments) {
    let times = departments.map(d => {
      return d.modifyTime
    }).sort()
    let lastTime = new Date()
    if (times.length > 0) {
      lastTime = times[0]
    }
    state.chooseDepart++
    Vue.prototype.$DesignDB.updateDepartments(departments, lastTime)
  },
  updateEmployees (state, employees) {
    let times = employees.map(d => {
      return d.modifyTime
    }).sort()
    let lastTime = new Date()
    if (times.length > 0) {
      lastTime = times[0]
    }
    Vue.prototype.$DesignDB.updateEmployees(employees, lastTime)
    state.chooseEmployees++
  },
  updateEmployeesCount (state, payload) {
    const coId = Vue.prototype.$store.getters.currentUser.coId
    Vue.prototype.$DesignDB.employeesCount(coId, 1, payload).then((count) => {
      state.employeesCount.onJob = count
    })
    Vue.prototype.$DesignDB.employeesCount(coId, 2, payload).then((count) => {
      state.employeesCount.offJob = count
    })
    Vue.prototype.$DesignDB.adminCount(coId, payload).then((count) => {
      state.employeesCount.admin = count
    })
  }
}

// 获取数据
const actions = {
  actSyncContacts ({commit}, payload) {
    return new Promise((resolve) => {
      commit({
        type: 'syncContacts'
      })
      resolve()
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
